package saucaca.fragment;

import java.util.ArrayList;

import lemon.kenhnhacvn.BaseEngine;
import lemon.kenhnhacvn.MainActivity;
import lemon.kenhnhacvn.R;

import org.json.JSONException;

import saucaca.Adapter.PlaylistAdapter;
import saucaca.CustomView.XListView;
import saucaca.JSON.JsonReader;
import saucaca.JSON.WServiceLib;
import saucaca.Object.HomeData;
import saucaca.Object.PlaylistObject;
import saucaca.Util.PreferenceUtils;
import saucaca.Util.TagName;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;


public class SelectPlaylistDialogFragment extends DialogFragment {
	ArrayList<PlaylistObject> listPlaylist;
	String songId;
	ViewGroup rootView;
	XListView mView_listView;
	PlaylistAdapter adapter;
	private ProgressBar progressBar;
	ImageView imgEmpty, imgError;
	TextView txtStatus;
	private View mView_EmptyLoading = null;
	Button buttonCreate;
	private final int CONTEXT_MENU_RENAME = 1;
	private final int CONTEXT_MENU_DELETE = 2;
	private final int CONTEXT_MENU_PLAYLATER = 3;

	// private PopupMenu mOverflowPopupMenu = null;

	public static SelectPlaylistDialogFragment newInstance(String SongId) {
		SelectPlaylistDialogFragment f = new SelectPlaylistDialogFragment();
		Bundle args = new Bundle();
		args.putString(MainActivity.ID, SongId);
		f.setArguments(args);
		return f;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (getArguments() != null) {
			songId = getArguments().getString(MainActivity.ID);
		} else {
			TagName.showToastShort(getActivity(), "Arguments nullll!!!!!!!!!!!!!");
		}
		new GetPlaylist().execute("");
		initViewsSetting();
	}

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		AlertDialog dialog = new AlertDialog.Builder(getActivity()).setTitle(R.string.string_playlist).setView(rootView)
				.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dismiss();
					}
				}).create();
		return dialog;
	}

	private void initViewsSetting() {
		LayoutInflater inflater = LayoutInflater.from(getActivity());
		rootView = (ViewGroup) inflater.inflate(R.layout.playlist_show, null, false);
		mView_listView = (XListView) rootView.findViewById(R.id.layoutlistview_listview);
		mView_listView.setPullLoadEnable(false);
		mView_listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				PlaylistObject playlistObject = listPlaylist.get(position);
				String Playid = playlistObject.getALBUM_ID();
				String Playname = playlistObject.getTXNAME();
				String[] params = { Playid, Playname };
				new addplaylistService().execute(params);
			}
		});
		mView_EmptyLoading = rootView.findViewById(R.id.empty_loading);
		mView_listView.setEmptyView(mView_EmptyLoading);
		mView_listView.startProgressBar();
		progressBar = (ProgressBar) mView_EmptyLoading.findViewById(R.id.empty_loading_progress);
		imgEmpty = (ImageView) mView_EmptyLoading.findViewById(R.id.empty_loading_NoItem);
		imgError = (ImageView) mView_EmptyLoading.findViewById(R.id.empty_loading_Error);
		txtStatus = (TextView) mView_EmptyLoading.findViewById(R.id.empty_loading_text);
		buttonCreate = (Button) rootView.findViewById(R.id.btn_footer);
		buttonCreate.setVisibility(View.GONE);
		buttonCreate.setText("Create New Playlist");
		buttonCreate.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				newPlayListDialog();
			}
		});
	}

	class GetPlaylist extends AsyncTask<String, String, String> {
		@Override
		protected String doInBackground(String... params) {
			String str = WServiceLib.playlist("", "", PreferenceUtils.getString(getActivity(), TagName.KeyPreference_user));
			BaseEngine.showLogformLongString(str);
			return str;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (result != null)
				try {
					listPlaylist = JsonReader.listPlaylist(result);
					if (listPlaylist.size() > 0) {
						adapter = new PlaylistAdapter(getActivity(), listPlaylist);
						mView_listView.setAdapter(adapter);
					} else {
						progressBar.setVisibility(View.GONE);
						imgEmpty.setVisibility(View.VISIBLE);
						txtStatus.setText("Chưa có Playlist");
					}
					buttonCreate.setVisibility(View.VISIBLE);
					mView_listView.stopProgressBar();
				} catch (JSONException e) {
					e.printStackTrace();
				}
		}
	}

	class addplaylistService extends AsyncTask<String[], String, String> {
		ProgressDialog progressDialog = new ProgressDialog(getActivity());
		@Override
		protected String doInBackground(String[]... params) {
			String playId = params[0][0];
			String playName = params[0][1];
			String str = WServiceLib.playlistAdd(playId, songId, PreferenceUtils.getString(getActivity(), TagName.KeyPreference_user), playName);
			return str;
		}
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if (!progressDialog.isShowing())
				progressDialog.show();
		}
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (progressDialog.isShowing())
				progressDialog.hide();
			if (result != null)
				try {
					JsonReader.readHeader(result);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			if (HomeData.headerObject.getCODE().equals("0")) {
				new GetPlaylist().execute("");
			}
			TagName.showToastShort(getActivity(), HomeData.headerObject.getMESSAGE());
		}
	}

	private void newPlayListDialog() {
		AlertDialog.Builder builder = new Builder(getActivity());
		builder.setTitle("Tạo Playlist Online");
		final EditText tv = new EditText(getActivity());
		tv.setHint("Playlist name");
		builder.setView(tv);
		builder.setPositiveButton("OK", new android.content.DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				String namePlaylist = tv.getText().toString();
				String[] params = { "0", namePlaylist };
				if (namePlaylist != null) {
					new addplaylistService().execute(params);
				}
			}
		});
		builder.setNegativeButton("Cancel", new android.content.DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.create().show();
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		final AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
		menu.setHeaderTitle(listPlaylist.get(info.position).getTXNAME());
		// menu.add(0, CONTEXT_MENU_PLAYLATER, Menu.NONE, R.string.play_later);
		menu.add(0, CONTEXT_MENU_RENAME, Menu.NONE, R.string.popup_menu_rename);
		menu.add(0, CONTEXT_MENU_DELETE, Menu.NONE, R.string.popup_menu_delete);
	}
}
